//
//  HSYBaseQRCodeViewController+Manager.m
//  高仿暴走斗图
//
//  Created by key on 16/3/23.
//  Copyright © 2016年 huangsongyao. All rights reserved.
//

#import "HSYBaseQRCodeViewController+Manager.h"

static NSString *kHSYQRCodeScanningAnimationKey  = @"HSYQRCodeScanningAnimationKey";

@implementation HSYBaseQRCodeViewController (Manager)

- (void)starQRCodeAnimationInLayer:(CALayer *)layer toY:(NSNumber *)toY completion:(void(^)())completion {
    
    CABasicAnimation *animation = [HSYBaseQRCodeViewController moveYTime:2 fromY:@(0) toY:toY rep:OPEN_MAX];
    [layer addAnimation:animation forKey:kHSYQRCodeScanningAnimationKey];
    
    completion();
}

+ (CABasicAnimation *)moveYTime:(CGFloat)time fromY:(NSValue *)fromY toY:(NSValue *)toY rep:(CGFloat)rep {
    
    CABasicAnimation *animationMove = [CABasicAnimation animationWithKeyPath:@"transform.translation.y"];
    animationMove.fromValue = fromY;
    animationMove.toValue = toY;
    animationMove.duration = time;
    animationMove.delegate = self;
    animationMove.repeatCount  = rep;
    animationMove.fillMode = kCAFillModeForwards;
    animationMove.removedOnCompletion = NO;
    animationMove.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    
    return animationMove;
}


- (void)removeQRCodeAnimationInLayer:(CALayer *)layer completion:(void(^)())completion {
    
    [layer removeAnimationForKey:kHSYQRCodeScanningAnimationKey];
    completion();
}


- (CGRect)getScanLayerInViewForRect:(CGRect)rect readerViewBounds:(CGRect)readerViewBounds {
    
    CGFloat fullWidth = CGRectGetWidth(readerViewBounds);
    CGFloat fullHeight = CGRectGetHeight(readerViewBounds);
    
    CGFloat x = CGRectGetMinX(rect);
    CGFloat y = CGRectGetMinY(rect);
    
    CGFloat width = CGRectGetWidth(rect);
    CGFloat height = CGRectGetHeight(rect);
    
    if (x + width > fullWidth) {
        if (width > fullWidth) {
            width = fullWidth;
        } else {
            x = 0;
        }
    }
    
    if (y + height > fullHeight) {
        if (height > fullHeight) {
            height = fullHeight;
        } else {
            y = 0;
        }
    }
    
    CGFloat x1, y1, width1, height1;
    x1 = (fullWidth - width - x) / fullWidth;
    y1 = y / fullHeight;
    width1 = width / fullWidth;
    height1 = rect.size.height / readerViewBounds.size.height;
    
    NSLog(@"frame:%@",NSStringFromCGRect(CGRectMake(y1, x1,height1, width1)));
    return CGRectMake(y1, x1, height1, width1);
}


@end
